package services;

import dao.NewsDAO;
import dao.exception.DAOException;
import entities.News;
import parser.news.NewsParser;

import javax.ejb.EJB;
import javax.ejb.Stateless;
import java.util.List;
import java.util.logging.Level;

/**
 * Service for work with news
 * User: kaiser
 * Date: 7/31/13
 * Time: 9:16 PM
 */
@Stateless
public class NewsService {

    private final java.util.logging.Logger logger = java.util.logging.Logger.getLogger(NewsService.class.getName());

    @EJB
    NewsDAO newsDAO;

    @EJB
    ChannelService channelService;

    /**
     * Getting channels news, <br/>
     * first in list is most popular and new
     *
     * @param name Channel primary name
     * @return List of newest
     * @throws ServiceException if try get news for a non-existent channel
     */
    public List<News> getChannelNews(String name) throws ServiceException {
        if (!channelService.isChannelExist(name)) {
            throw new ServiceException("Channel " + name + " not exist");
        }

        return newsDAO.getNewsByChannel(name, NewsParser.DEFAULT_NEWS_COUNT);
    }

    /**
     * Get list of most popular and newest news
     *
     * @return List of news
     */
    public List<News> getTopNews() {
        return newsDAO.getTopNews(NewsParser.DEFAULT_NEWS_COUNT);
    }

    /**
     * increase news rate on 1
     *
     * @param newsId News id for increase rate
     * @throws ServiceException if try to increase not existing news
     */
    public void upNewsRank(int newsId) throws ServiceException {
        if (newsDAO.isExist(newsId)) {
            newsDAO.upNewsRank(newsId);
        } else {
            throw new ServiceException("News with " + newsId + "not exist");
        }

    }

    /**
     * Persist in DB new news
     *
     * @param newsList news list to persist
     * @throws ServiceException if list is null or some DAOException occurred
     */
    public void addNewNews(List<News> newsList) throws ServiceException {
        if (newsList != null) {
            for (News news : newsList) {
                if (!newsDAO.isExist(news)) {
                    logger.log(Level.INFO, "[ADD NEWS]" + news);
                    try {
                        newsDAO.create(news);
                    } catch (DAOException e) {
                        throw new ServiceException(e);
                    }
                }
            }
        } else {
            throw new ServiceException("Unable to add new news list is NULL");
        }
    }

    /**
     * Remove not popular old chanel news.
     *
     * @param channel             channel primary name old news which will be removed
     * @param inviolableNewsCount count of news to left
     */
    public void removeOldNotPopularNews(String channel, int inviolableNewsCount) {
        if (channel != null && inviolableNewsCount != 0) {
            newsDAO.removeOldNotPopularNews(channel, inviolableNewsCount);
        }
    }
}
